package com.stark.commons.spring.web.support.multipart;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.web.multipart.MultipartFile;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Accessors;

/**
 * 内存存储文件的 {@link MultipartFile} 接口实现。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
@Data
@Accessors(chain = true)
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
public class ByteArrayMultipartFile implements MultipartFile {

	private String name = "file";

	@NonNull
	private String originalFilename;

	@NonNull
	private byte[] bytes;

	private String contentType;

	@Override
	public boolean isEmpty() {
		return bytes.length == 0;
	}

	@Override
	public long getSize() {
		return bytes.length;
	}

	@Override
	public InputStream getInputStream() {
		return new ByteArrayInputStream(bytes);
	}

	@Override
	public void transferTo(File destination) throws IOException {
		OutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(destination);
			outputStream.write(bytes);
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
	}
	
}
